package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(tags = "C端-地址博接口")
@RequestMapping("/user/addressBook")
public class AddressBookController {
@Autowired
    private AddressBookService addressBookService;

    /**
     * 查询当前用户所有端地址信息
     * @return
     */
    @ApiOperation("查询当前用户所有端地址信息")
    @GetMapping("/list")
public Result<List<AddressBook>> list(){
    log.info("查询当前用户所有端地址信息:{}",BaseContext.getCurrentId());
    AddressBook addressBook = new AddressBook();
    addressBook.setUserId(BaseContext.getCurrentId());
    List<AddressBook> list = addressBookService.list(addressBook);

    return Result.success(list);

}

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
@ApiOperation("新增地址")
public Result save(@RequestBody AddressBook addressBook){
        log.info("新增地址:{}",addressBook);
        addressBookService.save(addressBook);
        return Result.success();
}

    /**
     * 根据id查询地址
     * @return
     */
    @ApiOperation("根据id查询地址")
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id){
        log.info("根据id查询地址:{}",id);

        AddressBook list = addressBookService.getById(id);

        return Result.success(list);

    }

    /**
     * 根据id修改地址
     * @return
     */
    @ApiOperation("根据id修改地址")
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook){
        log.info("根据id修改地址:{}",addressBook);

        addressBookService.update(addressBook);

        return Result.success();

    }

    /**
     * 设置默认地址
     * @return
     */
    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook){
        log.info("设置默认地址:{}",addressBook);

        addressBookService.setDefault(addressBook);

        return Result.success();

    }

    /**
     * 根据id删除地址
     * @return
     */
    @ApiOperation("根据id删除地址")
    @DeleteMapping
    public Result delete(  Long id){
        log.info("根据id删除地址:{}",id);

        addressBookService.deleteById(id);

        return Result.success();

    }

    /**
     * 设置默认地址
     * @return
     */
    @ApiOperation("设置默认地址")
    @GetMapping("/default")
    public Result<AddressBook> getByDefault(){

        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);

        List<AddressBook> list = addressBookService.list(addressBook);
        if (list==null && list.size()==0){
            return Result.error("没有查询到默认地址");
        }

        return Result.success(list.get(0));

    }

}
